import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { useUserStore } from '@/stores/user';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta:{requiresAuth: true}
    },
    {
      path: "/profile",
      name: "user-profile",
      component: () => import("../views/user/ProfileView.vue"),
      meta: { requiresAuth: true }
      },
    {
      path: "/login",
      name: "user-login",
      component: () => import("../views/user/LoginView.vue"),
      meta:{requiresAuth: false}
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue')
    },
    {
      path: "/:pathMatch(.*)*",
      name: "not-found",
      component: () => import("../views/NotFoundView.vue"),
      meta:{requiresAuth: false}
      }
      
  ]
});
//前置路由守卫
router.beforeEach((to) => {
  const store = useUserStore();
  const isLogin = store.isLogin;
  console.log(`to:${to.fullPath},isLogin:${isLogin}`);
  //登录状态服务端校验
  if (to.meta.requiresAuth && isLogin) {
    console.log("后端校验权限");
    store.isAuth();
   }
  //防止登录页循环访问
  if (isLogin && to.name === "user-login") {
   return { path: "/" };
  }
 
  //未登录且需要访问权限，跳转到登录路由
  if(to.meta.requiresAuth && !isLogin){
  return {
   path: "/login"
  }
 }
});

export default router
